<template>
	<u-skeleton :rowsHeight="['265px', '18px', '80px']" :loading="loading" :animate="true" rows="20" title>
		<view class="content">
			<Head  :list1="list1" :communities="communityList"
			 :current-community="currentCommunity"/>
			<view class="content-setions">
				<Notice :noticeList="noticeList" :loginStatus="loginStatus" />
				<NewCard :loginStatus="loginStatus" />
				<!-- <view @click="navto()">跳转</view> -->
				<!-- 菜单 -->
				<!-- <Menus :menuList="menuList" /> -->
				<!-- 菜单结束 -->
				<!-- 投票 -->
				<VoteCard title="业主大会"
				 :vote-list="voteList1" :type="1" />
				<!-- <VoteCard 
				title="快速决议"
				 :vote-list="voteList2" :type="2" />
				<VoteCard title="问卷调查"
				 :vote-list="voteList3" :type="3" />
				<VoteCard title="倡议书" 
				:vote-list="voteList4" :type="4" /> -->
				
				<!-- 投票 结束-->
			</view>

		</view>
	</u-skeleton>
</template>

<script>
	import Head from './components/Head.vue'
	import Menus from './components/Menus.vue'
	import VoteCard from './components/VoteCard.vue'
	import Notice from './components/Notice.vue'
	import NewCard from './components/NewCard.vue'
	

	import {
		getCommunity,getBindInfo,getVoteList,getAreas,
		getNoticeList
	} from '@/api/index'
	import {
		mapState,
		mapMutations,
		mapActions
	} from 'vuex'
	import ls from '@/util/ls'
	import { name } from '@/util/config'
	import { parseSceneParams,findCityNameByCode } from '@/util/function'

	export default {
		components: {
			Head,
			Menus,
			Notice,
			NewCard,
			
			VoteCard
		},
		data() {
			return {
				loading: true,
				noticeList:[],
				title: 'Hello',
				list1: [
					"https://ainij.oss-cn-beijing.aliyuncs.com/pms/202506/1.png",
					"https://ainij.oss-cn-beijing.aliyuncs.com/pms/202506/2.png"
				],
				menuList: [],
				communityList: [],
				currentCommunity: {},
				
				voteList: [],
				voteList1: [], // 业主大会
				voteList2: [], // 快速决议
				voteList3: [], // 问卷调查
				voteList4: [], // 倡议书
				query:{
					communityId:null,
					pageNum:1,
					pageSize:5
				},
				total:0,
				// userInfo:ls.get("user") || {}
				isFirstLoad: true, // 添加标志位
				
			}
		},
		computed:{
			...mapState("app",[
				'loginStatus','userInfo'
			]),
		
			...mapState("community",["boundHouses","communityId"])
		},
		watch:{
			loginStatus(newVal){
				if(this.isFirstLoad) return; // 第一次不执行
				console.log("newVal",newVal)
				if(newVal==1){
						this.getCommunityList();
						this.getVoteList(1);
				}
			},
			communityId(newVal,oldVal){
				if(this.isFirstLoad) return; // 第一次不执行
			
                
				// if(oldVal!=-1){	}
				
					let item=this.communityList.find(item=>{
						
						return item.communityId==newVal.toString()
					})
					console.log("newvalue",newVal,item)
					if(item){
					console.log("监听")
					this.handleCommunityChange(this.communityList.find(item=>item.communityId==newVal))
				    }
			
			
			}
		},
		onLoad(params) {
			this.init(params)
			// 延迟标记初始化完成
			
		},
		// 下拉刷新
		onPullDownRefresh() {
			this.refreshPage()
		},
		 onShareAppMessage(res) {
				return {
				imageUrl:"",	
				title: name,
				path: `/pages/home/index?communityId=${this.currentCommunity.communityId}`
				}
			},
		
		methods: {
			...mapMutations("community",[
				'setCommunityId',
				'setBoundHouses',
				'setCommunityName',
				'setLocation',
				 "setCommunityInfo"
			]),
			async init(params) {
				const systemInfo = wx.getSystemInfoSync();
				// 获取安全区域信息
				const safeArea = systemInfo.safeArea;
				const screenHeight = systemInfo.screenHeight;
				// 计算底部安全区域高度
               const bottomSafeAreaHeight = screenHeight - safeArea.bottom;
			 
			
				setTimeout(() => {
					this.loading = false
				}, 100 * 3)
				
				if(params.scene){
					params=parseSceneParams(params)
					
				}
				if(params.communityId){
					this.setCommunityId(params.communityId)
				}
				let t= setTimeout(()=>{
                 this.isFirstLoad = false;
				 clearTimeout(t)
				},3000)
               console.log("this.communityId",this.communityId)
				this.getCommunityList(this.communityId || params.communityId);
			
			

			},
			 async getNotices(communityId){
              	let data=await getNoticeList({
					pageNum:1,
					pageSize:10,
					communityId
				})
				this.noticeList=data.rows
				
			},
			async getCommunityNameInfo(id){ //获取单独小区的信息
					 let res = await getAreas({});
					let data=this.communityList.find(e=>e.communityId==id)
				    let data1 = findCityNameByCode(data.cityCode, res.rows)
                   if(data1){
                    this.setLocation({
					city: data1.provinceName,
					province: data1.cityName,
					provinceCode: data1.provinceCode,
					cityCode:  data1.cityCode
				   })
						
				   }
				
				
			},
			async getCommunityList(communityId=undefined) {
				let data=await getCommunity({
					pageNum: 1,
                   pageSize: 1000
				})
				if(Array.isArray(data.rows)&&data.rows.length>0){
				this.communityList=data.rows
				if(communityId&&communityId!=-1){
					this.currentCommunity = this.communityList.find(item=>item.communityId==communityId)
				}else{
					let lsCommunityId=ls.get("communityId")
					let lsCommunityName=ls.get("communityName")
					if(lsCommunityId){
						this.currentCommunity = this.communityList.find(item=>item.communityId==lsCommunityId)
					    let obj={
							lsCommunityId,
							lsCommunityName:lsCommunityName||""
						}
						this.setCommunityInfo(obj)
					}else{
					 return
					}
					// this.currentCommunity = this.communityList[0];
					
				}
				
           
				this.getCommunityNameInfo(this.currentCommunity.communityId)
				this.$nextTick(()=>{
					
					this.setCommunityId(this.currentCommunity.communityId)
					this.setCommunityName(this.currentCommunity.name)
					this.$nextTick(()=>{
						this.getVoteList(2);
						this.newVoteList();
						this.getNotices(this.currentCommunity.communityId)
					})
					
				})
			
				}
			},
			handleCommunityChange(community) {
				console.log("我触发了handleCommunityChange",community.communityId)
			  
				this.currentCommunity = community;
				this.voteList=[]
				this.voteList1=[]
				this.voteList2=[]
				this.voteList3=[]
				this.voteList4=[]
				this.$nextTick(()=>{
					this.getVoteList(3);
					this.newVoteList();
					this.getNotices(this.currentCommunity.communityId)
				})
			},
			geList() {
				this.menuList = [{
						name: '业主变更',
						src: this.getImg('home_menus_1.svg'),
						width: "42.58px",

					},
					{
						name: '产权认证',
						src: this.getImg('home_menus_2.svg'),
						width: "42.58px",

					},
					{
						name: '智慧顾问',
						src: this.getImg('home_menus_3.svg'),
						width: "42.58px",

					},
					{
						name: '入驻适应',
						src: this.getImg('home_menus_4.svg'),
						width: "42.58px",

					},
				]
			},
			navto(name) {

			  uni.navigateTo({
				url: '/pages/bindhouse/index?communityId='+this.currentCommunity.communityId
			  })
			},
			async newVoteList(){
			
				// 请求4种不同类型的投票
				const voteTypes = [
					{ type: 1, title: '业主大会', listKey: 'voteList1' },
					{ type: 2, title: '快速决议', listKey: 'voteList2' },
					{ type: 3, title: '问卷调查', listKey: 'voteList3' },
					{ type: 4, title: '倡议书', listKey: 'voteList4' }
				]
				
				// 并行请求所有类型的投票数据
				const promises = voteTypes.map(async ({ type, listKey }) => {
					try {
						let data = await getVoteList({
							communityId: this.communityId,
							pageNum: this.query.pageNum,
							pageSize: this.query.pageSize,
							type: type
						})
						
						if (data.rows) {
							this[listKey] = [...data.rows]
						}
						return { type, total: data.total }
					} catch (error) {
						console.error(`获取类型${type}投票失败:`, error)
						this[listKey] = []
						return { type, total: 0 }
					}
				})
				
				// 等待所有请求完成
				const results = await Promise.all(promises)
				
				// 计算总数量
				this.total = results.reduce((sum, result) => sum + result.total, 0)
               
			},
			async getVoteList(index) {
			
				let userInfo=ls.get("user") || {}
				let wxUserId=""
				if(this.userInfo){
                  wxUserId=this.userInfo.wxUser.wxUserId
				}else if(userInfo){
				 wxUserId=userInfo.wxUser.wxUserId
				}else{
					return
				}
				
			
				let communityId= this.communityId ||this.currentCommunity.communityId 
				
				let data2=await getBindInfo({
					communityId: communityId,
					liveUserId: wxUserId,
					auditStatus:2
				})
				
				this.setBoundHouses(data2.rows.length)
			},
			// 下拉刷新页面
			async refreshPage() {
				try {
					// 如果没有选择小区，不执行刷新
					if (!this.currentCommunity || !this.currentCommunity.communityId) {
						uni.stopPullDownRefresh()
						return
					}
					
					// 刷新投票列表
					await this.newVoteList()
					
					// 刷新公告列表
					await this.getNotices(this.currentCommunity.communityId)
					
					// 刷新绑定房屋数量
					await this.getVoteList(4)
					
					// 停止下拉刷新动画
					uni.stopPullDownRefresh()
					
					// 提示刷新成功
					uni.showToast({
						title: '刷新成功',
						icon: 'success',
						duration: 1500
					})
				} catch (error) {
					console.error('刷新失败:', error)
					uni.stopPullDownRefresh()
					uni.showToast({
						title: '刷新失败',
						icon: 'none',
						duration: 1500
					})
				}
			}
		}
	}
</script>

<style lang="scss">
	page {
		width: 100%;
		height: 100%;
	}

	.content-setions {
		width: 100%;
		padding: 0 36rpx;
		//   background: linear-gradient(180deg, #F8FAFD 0%, #F8FAFD 100%);
	}

	.content {
		width: 100%;
		min-height: 100vh;
		background: linear-gradient(180deg, #f8fafd 0%, #F8FAFD 100%);
	}
</style>